package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Spawns;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;

import java.util.Objects;

public class FishpoolScene extends FXGLScene {
    private StackPane sceneRoot;
    public static int fishCount = 0;
    public static int greenFishCount = 0;
    public static int grayFishCount = 0;
    public static int brownFishCount = 0;
    // 新增：橙鱼和粉鱼数量
    public static int orangeFishCount = 0;
    public static int pinkFishCount = 0;
    // 新增：鱼王数量和实体列表
    public static int redKingFishCount = 0;
    // 新增：第二阶段鱼类数量
    public static int liangziFishCount = 0; // 良子鱼
    public static int caveSharkCount = 0;   // 洞穴鲨鱼
    public static int arcticShrimpCount = 0;
    private java.util.List<com.almasb.fxgl.entity.Entity> fishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> greenFishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> grayFishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> brownFishEntities = new java.util.ArrayList<>();
    // 新增：橙鱼和粉鱼实体列表
    private java.util.List<com.almasb.fxgl.entity.Entity> orangeFishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> pinkFishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> redKingFishEntities = new java.util.ArrayList<>();
    // 新增：第二阶段鱼类实体列表
    private java.util.List<com.almasb.fxgl.entity.Entity> liangziFishEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> caveSharkEntities = new java.util.ArrayList<>();
    private java.util.List<com.almasb.fxgl.entity.Entity> arcticShrimpEntities = new java.util.ArrayList<>();
    private com.almasb.fxgl.entity.Entity backgroundEntity;
    // 新增：定时器
    private javafx.animation.Timeline incomeTimeline;
    // 1. 类成员区
    private javafx.animation.Timeline moneyHudTimeline;
    private javafx.scene.control.Label moneyLabel;

    public FishpoolScene() {
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        initUI();
    }

    protected void initUI() {
        // 初始化根容器
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");

        // 每次进入都生成背景
        backgroundEntity = FXGL.entityBuilder()
                .at(0, 0)
                .view(new ImageView(new Image(Objects.requireNonNull(
                        getClass().getResourceAsStream("/assets/textures/FishpondBackground.png")))))
                .zIndex(0)
                .buildAndAttach();

        // 主界面切换时不再stopAll，只在未播放时播放HomeMusic
        if (comgame.scenes.MusicManager.homeMusic == null)
            comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
        comgame.scenes.MusicManager.isHomeMusicPlaying = true;
        System.out.println("[HomeMusic] FishpoolScene loopMusic已调用");

        // 清空所有鱼实体，防止重复生成
        removeFishEntities();
        orangeFishEntities.clear();
        pinkFishEntities.clear();
        redKingFishEntities.clear();

        // 清空所有鱼实体，防止重复生成
        removeFishEntities();
        orangeFishEntities.clear();
        pinkFishEntities.clear();
        redKingFishEntities.clear();

        // 只在第一次进入时初始化鱼数量
        if (fishCount == 0) {
            fishCount = 3;
        }

        // 生成 fishCount 条鱼，并保存引用
        for (int i = 0; i < fishCount; i++) {
            int x = 100 + (i % 3) * 200;
            int y = 100 + (i / 3) * 150;
            fishEntities.add(FXGL.spawn("RedFish", x, y));
        }
        // 生成 greenFishCount 条绿鱼
        for (int i = 0; i < greenFishCount; i++) {
            int x = 150 + (i % 3) * 200;
            int y = 200 + (i / 3) * 150;
            greenFishEntities.add(FXGL.spawn("GreenFish", x, y));
        }
        // 生成 grayFishCount 条灰鱼
        for (int i = 0; i < grayFishCount; i++) {
            int x = 200 + (i % 3) * 200;
            int y = 350 + (i / 3) * 150;
            grayFishEntities.add(FXGL.spawn("GrayFish", x, y));
        }
        // 生成 brownFishCount 条棕鱼
        for (int i = 0; i < brownFishCount; i++) {
            int x = 250 + (i % 3) * 200;
            int y = 500 + (i / 3) * 150;
            brownFishEntities.add(FXGL.spawn("BrownFish", x, y));
        }
        // 新增：生成 orangeFishCount 条橙鱼
        for (int i = 0; i < orangeFishCount; i++) {
            int x = 300 + (i % 3) * 200;
            int y = 150 + (i / 3) * 150;
            orangeFishEntities.add(FXGL.spawn("OrangeFish", x, y));
        }
        // 新增：生成 pinkFishCount 条粉鱼
        for (int i = 0; i < pinkFishCount; i++) {
            int x = 350 + (i % 3) * 200;
            int y = 250 + (i / 3) * 150;
            pinkFishEntities.add(FXGL.spawn("PinkFish", x, y));
        }
        // 新增：生成 redKingFishCount 条鱼王
        for (int i = 0; i < redKingFishCount; i++) {
            int x = 400 + (i % 3) * 200;
            int y = 350 + (i / 3) * 150;
            redKingFishEntities.add(FXGL.spawn("RedKingFish", x, y));
        }
        
        // 新增：生成 liangziFishCount 条良子鱼
        for (int i = 0; i < liangziFishCount; i++) {
            int x = 450 + (i % 3) * 200;
            int y = 450 + (i / 3) * 150;
            liangziFishEntities.add(FXGL.spawn("LiangziFish", x, y));
        }
        
        // 新增：生成 caveSharkCount 条洞穴鲨鱼
        for (int i = 0; i < caveSharkCount; i++) {
            int x = 500 + (i % 3) * 200;
            int y = 550 + (i / 3) * 150;
            caveSharkEntities.add(FXGL.spawn("CaveShark", x, y));
        }

        // 新增：生成 arcticShrimpCount 条北极甜虾
        for (int i = 0; i < arcticShrimpCount; i++) {
            int x = 600 + (i % 3) * 100;
            int y = 200 + (i / 3) * 100;
            arcticShrimpEntities.add(FXGL.spawn("ArcticShrimp", x, y));
        }

        // 横向排列所有鱼的购买按钮
        HBox fishBtnBox = new HBox(30); // 按钮间距30像素
        fishBtnBox.setAlignment(Pos.TOP_CENTER);
        fishBtnBox.setPadding(new Insets(20, 0, 0, 0));

        Button buyFishBtn = createSingleImageButton(
                "/assets/textures/fish_red.png",
                "买鱼(30)",
                0.8
        );
        Tooltip redFishTooltip = new Tooltip("购买价格: 30金币\n每5秒收益: 1金币");
        redFishTooltip.setShowDelay(javafx.util.Duration.millis(250));
        buyFishBtn.setTooltip(redFishTooltip);
        buyFishBtn.setOnMouseClicked(e -> {
            FXGL.play("fishing.wav");
            if (comgame.scenes.GameScene.player != null) {
                if (fishCount >= 20) {
                    FXGL.showMessage("红鱼最多只能拥有20只！");
                    return;
                }
                if (comgame.scenes.GameScene.player.getMoney() >= 30) {
                    comgame.scenes.GameScene.player.addMoney(-30);
                    fishCount++;
                    int x = 100 + ((fishCount-1) % 3) * 200;
                    int y = 100 + ((fishCount-1) / 3) * 150;
                    fishEntities.add(FXGL.spawn("RedFish", x, y));
                } else {
                    FXGL.showMessage("金币不足！");
                }
            }
        });
        fishBtnBox.getChildren().add(buyFishBtn);

        Button buyGreenFishBtn = createSingleImageButton(
                "/assets/textures/fish_green.png",
                "买绿鱼(240)",
                0.8
        );
        Tooltip greenFishTooltip = new Tooltip("购买价格: 240金币\n每5秒收益: 8金币");
        greenFishTooltip.setShowDelay(javafx.util.Duration.millis(250));
        buyGreenFishBtn.setTooltip(greenFishTooltip);
        buyGreenFishBtn.setOnMouseClicked(e -> {
            FXGL.play("fishing.wav");
            if (comgame.scenes.GameScene.player != null) {
                if (greenFishCount >= 10) {
                    FXGL.showMessage("绿鱼最多只能拥有10只！");
                    return;
                }
                if (comgame.scenes.GameScene.player.getMoney() >= 240) {
                    comgame.scenes.GameScene.player.addMoney(-240);
                    greenFishCount++;
                    int x = 150 + ((greenFishCount-1) % 3) * 200;
                    int y = 200 + ((greenFishCount-1) / 3) * 150;
                    greenFishEntities.add(FXGL.spawn("GreenFish", x, y));
                } else {
                    FXGL.showMessage("金币不足！");
                }
            }
        });
        fishBtnBox.getChildren().add(buyGreenFishBtn);

        Button buyGrayFishBtn = createSingleImageButton(
                "/assets/textures/fish_grey.png",
                "买灰鱼(900)",
                0.6
        );
        Tooltip grayFishTooltip = new Tooltip("购买价格: 900金币\n每5秒收益: 30金币");
        grayFishTooltip.setShowDelay(javafx.util.Duration.millis(250));
        buyGrayFishBtn.setTooltip(grayFishTooltip);
        buyGrayFishBtn.setOnMouseClicked(e -> {
            FXGL.play("fishing.wav");
            if (comgame.scenes.GameScene.player != null) {
                if (grayFishCount >= 5) {
                    FXGL.showMessage("灰鱼最多只能拥有5只！");
                    return;
                }
                if (comgame.scenes.GameScene.player.getMoney() >= 900) {
                    comgame.scenes.GameScene.player.addMoney(-900);
                    grayFishCount++;
                    int x = 200 + ((grayFishCount-1) % 3) * 200;
                    int y = 350 + ((grayFishCount-1) / 3) * 150;
                    grayFishEntities.add(FXGL.spawn("GrayFish", x, y));
                } else {
                    FXGL.showMessage("金币不足！");
                }
            }
        });
        fishBtnBox.getChildren().add(buyGrayFishBtn);

        Button buyBrownFishBtn = createSingleImageButton(
                "/assets/textures/fish_brown.png",
                "买棕鱼(3000)",
                0.6
        );
        Tooltip brownFishTooltip = new Tooltip("购买价格: 3000金币\n每5秒收益: 80金币");
        brownFishTooltip.setShowDelay(javafx.util.Duration.millis(250));
        buyBrownFishBtn.setTooltip(brownFishTooltip);
        buyBrownFishBtn.setOnMouseClicked(e -> {
            FXGL.play("fishing.wav");
            if (comgame.scenes.GameScene.player != null) {
                if (brownFishCount >= 3) {
                    FXGL.showMessage("魔丸最多只能拥有3个！");
                    return;
                }
                if (comgame.scenes.GameScene.player.getMoney() >= 3000) {
                    comgame.scenes.GameScene.player.addMoney(-3000);
                    brownFishCount++;
                    int x = 250 + ((brownFishCount-1) % 3) * 200;
                    int y = 500 + ((brownFishCount-1) / 3) * 150;
                    brownFishEntities.add(FXGL.spawn("BrownFish", x, y));
                } else {
                    FXGL.showMessage("金币不足！");
                }
            }
        });
        fishBtnBox.getChildren().add(buyBrownFishBtn);

        sceneRoot.getChildren().add(fishBtnBox);

        // 添加返回按钮
        addBackButton();

        // 2. 在initUI()最后添加：
        moneyLabel = new javafx.scene.control.Label();
        moneyLabel.setText((comgame.scenes.GameScene.player != null ? comgame.scenes.GameScene.player.getMoney() : 0) + "￥");
        moneyLabel.setStyle("-fx-font-size: 28px; -fx-font-weight: bold; -fx-text-fill: #FFD700; -fx-background-color: rgba(0,0,0,0.18); -fx-padding: 8 18; -fx-background-radius: 12;");
        // 放在右上角
        StackPane.setAlignment(moneyLabel, Pos.TOP_RIGHT);
        StackPane.setMargin(moneyLabel, new Insets(12, 38, 0, 0));
        sceneRoot.getChildren().add(moneyLabel);
        // 实时刷新
        moneyHudTimeline = new javafx.animation.Timeline(
            new javafx.animation.KeyFrame(javafx.util.Duration.seconds(0.1), e -> updateMoneyHUD())
        );
        moneyHudTimeline.setCycleCount(javafx.animation.Animation.INDEFINITE);
        moneyHudTimeline.play();

        getContentRoot().getChildren().add(sceneRoot);
    }

    private void removeFishEntities() {
        for (var fish : fishEntities) {
            fish.removeFromWorld();
        }
        fishEntities.clear();
        for (var fish : greenFishEntities) {
            fish.removeFromWorld();
        }
        greenFishEntities.clear();
        for (var fish : grayFishEntities) {
            fish.removeFromWorld();
        }
        grayFishEntities.clear();
        for (var fish : brownFishEntities) {
            fish.removeFromWorld();
        }
        brownFishEntities.clear();
        // 新增：清空橙鱼和粉鱼
        for (var fish : orangeFishEntities) {
            fish.removeFromWorld();
        }
        orangeFishEntities.clear();
        for (var fish : pinkFishEntities) {
            fish.removeFromWorld();
        }
        pinkFishEntities.clear();
        // 新增：清空鱼王
        for (var fish : redKingFishEntities) {
            fish.removeFromWorld();
        }
        redKingFishEntities.clear();
        
        // 新增：清空第二阶段鱼类
        for (var fish : liangziFishEntities) {
            fish.removeFromWorld();
        }
        liangziFishEntities.clear();
        for (var fish : caveSharkEntities) {
            fish.removeFromWorld();
        }
        caveSharkEntities.clear();
        for (var shrimp : arcticShrimpEntities) {
            shrimp.removeFromWorld();
        }
        arcticShrimpEntities.clear();
    }

    // 添加返回按钮的方法
    private void addBackButton() {
        // 加载按钮音效（与GameScene保持一致）
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        // 创建返回按钮（使用与其他按钮一致的风格）
        Button backBtn = createSingleImageButton(
                "/assets/textures/back button3.png",  // 建议准备一个返回按钮图片
                "返回",
                0.1  // 缩放比例，可根据图片大小调整
        );

        // 设置按钮位置（左上角）
        StackPane.setAlignment(backBtn, Pos.TOP_LEFT);
        StackPane.setMargin(backBtn, new Insets(20, 0, 0, 20));  // 左上角边距

        // 绑定点击事件（返回GameScene）
        backBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            
            // 在返回前先保存当前数据，确保数据同步
            if (comgame.scenes.GameScene.player != null) {
                comgame.scenes.DataSaveManager.saveAll();
            }
            
            // 移除背景
            if (backgroundEntity != null) {
                backgroundEntity.removeFromWorld();
                backgroundEntity = null;
            }
            // 移除鱼实体
            removeFishEntities();
            FXGL.getGameScene().clearUINodes();
            GameScene gameScene = new GameScene();
            FXGL.getGameScene().addUINode(gameScene.getSceneRoot());
            // 确保player实体可见
            if (comgame.scenes.GameScene.playerEntity != null) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            }
        });

        // 将按钮添加到场景
        sceneRoot.getChildren().add(backBtn);
    }

    // 复用GameScene中的按钮创建方法（保持风格一致）
    private Button createSingleImageButton(String imagePath, String text, double scale) {
        // 加载图片
        Image buttonImage = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));

        // 创建按钮（不设置文本，只显示图片）
        Button button = new Button();
        ImageView imageView = new ImageView(buttonImage);

        // 应用缩放
        imageView.setFitWidth(buttonImage.getWidth() * scale);
        imageView.setFitHeight(buttonImage.getHeight() * scale);
        button.setGraphic(imageView);

        // 设置按钮尺寸
        button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());

        // 移除默认样式，但保留Tooltip功能
        button.setStyle("-fx-background-color: transparent; -fx-border-color: transparent; -fx-cursor: hand;");

        // 创建阴影效果（悬停时使用）
        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);

        // 设置按钮状态变化事件（与其他按钮保持一致的交互效果）
        button.setOnMouseEntered(e -> {
            button.setEffect(shadow);        // 添加阴影
            button.setOpacity(0.9);          // 轻微透明
        });

        button.setOnMouseExited(e -> {
            button.setEffect(null);          // 移除阴影
            button.setOpacity(1.0);          // 恢复不透明
        });

        button.setOnMousePressed(e -> {
            button.setOpacity(0.8);          // 点击时更透明
            button.setScaleX(0.98);          // 轻微缩小
            button.setScaleY(0.98);
        });

        button.setOnMouseReleased(e -> {
            button.setOpacity(0.9);          // 恢复悬停状态
            button.setScaleX(1.0);           // 恢复大小
            button.setScaleY(1.0);
        });

        return button;
    }

    // 3. 在FishpoolScene类内新增方法：
    private void updateMoneyHUD() {
        if (moneyLabel != null) {
            moneyLabel.setText((comgame.scenes.GameScene.player != null ? comgame.scenes.GameScene.player.getMoney() : 0) + "￥");
        }
    }

    public StackPane getSceneRoot() {
        return sceneRoot;
    }
    public static void resetFishCounts() {
        fishCount = 0;
        greenFishCount = 0;
        grayFishCount = 0;
        brownFishCount = 0;
        orangeFishCount = 0;
        pinkFishCount = 0;
        redKingFishCount = 0;
        liangziFishCount = 0;
        caveSharkCount = 0;
        arcticShrimpCount = 0;
    }
}
